import classNames from 'classnames'
import { useEffect, useRef } from 'react'
import styles from './index.module.scss'

interface Props
  extends React.DetailedHTMLProps<
    React.TextareaHTMLAttributes<HTMLTextAreaElement>,
    HTMLTextAreaElement
  > {
  className?: string
  value?: string
  maxLength?: number
}

export default function Textarea({
  className,
  maxLength = 100,
  value = '',
  ...res
}: Props) {
  const textareaRef = useRef<HTMLTextAreaElement>(null)

  useEffect(() => {
    textareaRef.current?.setSelectionRange(-1, -1)
  }, [])

  return (
    <div className={styles.root}>
      {/* 文本输入框 */}
      <textarea
        ref={textareaRef}
        {...res}
        className={classNames(className, 'textarea')}
        maxLength={maxLength}
        value={value}
      />
      {/* 当前字数/最大允许字数 */}
      <div className="count">
        {value.length}/{maxLength}
      </div>
    </div>
  )
}
